"""
for循环
学习目标：
1. 理解循环的概念
2. 掌握for循环的基本语法
3. 掌握range()函数的使用
4. 学会遍历各种数据结构
"""

# ==================== 1. for循环基础 ====================
print("=" * 50)
print("1. for循环基础")
print("=" * 50)

print("基本语法：")
print("""
for 变量 in 可迭代对象:
    循环体
""")

# 遍历列表
print("\n遍历水果列表：")
fruits = ["苹果", "香蕉", "橙子", "葡萄"]
for fruit in fruits:
    print(f"  - {fruit}")

print("\n💡 关键点：")
print("  - for循环用于遍历序列")
print("  - 每次循环，变量获得序列中的一个元素")
print("  - 循环体要缩进")

print()

# ==================== 2. range()函数 ====================
print("=" * 50)
print("2. range()函数 - 生成数字序列")
print("=" * 50)

# range(n)：从0到n-1
print("range(5)：")
for i in range(5):
    print(f"  {i}", end=" ")
print()

# range(start, stop)：从start到stop-1
print("\nrange(1, 6)：")
for i in range(1, 6):
    print(f"  {i}", end=" ")
print()

# range(start, stop, step)：指定步长
print("\nrange(0, 10, 2)：")
for i in range(0, 10, 2):
    print(f"  {i}", end=" ")
print()

# 倒序
print("\nrange(10, 0, -1)：")
for i in range(10, 0, -1):
    print(f"  {i}", end=" ")
print()

print("\n\n💡 range()用法：")
print("  range(n)         → 0 到 n-1")
print("  range(a, b)      → a 到 b-1")
print("  range(a, b, c)   → a 到 b-1，步长c")

print()

# ==================== 3. 遍历字符串 ====================
print("=" * 50)
print("3. 遍历字符串")
print("=" * 50)

text = "Python"
print(f"字符串：{text}")
print("每个字符：")
for char in text:
    print(f"  {char}")

print()

# ==================== 4. 遍历字典 ====================
print("=" * 50)
print("4. 遍历字典")
print("=" * 50)

student = {"name": "张三", "age": 18, "grade": "高三"}

# 遍历键
print("遍历键：")
for key in student:
    print(f"  {key}")

# 遍历值
print("\n遍历值：")
for value in student.values():
    print(f"  {value}")

# 遍历键值对
print("\n遍历键值对：")
for key, value in student.items():
    print(f"  {key}: {value}")

print()

# ==================== 5. 遍历索引和值 ====================
print("=" * 50)
print("5. enumerate() - 同时获取索引和值")
print("=" * 50)

fruits = ["苹果", "香蕉", "橙子"]
print("水果列表：")
for index, fruit in enumerate(fruits):
    print(f"  {index}: {fruit}")

# 指定起始索引
print("\n从1开始编号：")
for index, fruit in enumerate(fruits, start=1):
    print(f"  第{index}个：{fruit}")

print()

# ==================== 6. 实战：求和 ====================
print("=" * 50)
print("6. 实战：累加求和")
print("=" * 50)

# 求1到100的和
total = 0
for i in range(1, 101):
    total += i

print(f"1 + 2 + 3 + ... + 100 = {total}")

# 求列表元素的和
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
    total += num

print(f"\n列表{numbers}的和 = {total}")

print()

# ==================== 7. 实战：查找最大值和最小值 ====================
print("=" * 50)
print("7. 实战：查找最大值和最小值")
print("=" * 50)

scores = [85, 92, 78, 96, 88]
print(f"成绩列表：{scores}")

# 查找最大值
max_score = scores[0]
for score in scores:
    if score > max_score:
        max_score = score

print(f"最高分：{max_score}")

# 查找最小值
min_score = scores[0]
for score in scores:
    if score < min_score:
        min_score = score

print(f"最低分：{min_score}")

print()

# ==================== 8. 实战：打印图案 ====================
print("=" * 50)
print("8. 实战：打印图案")
print("=" * 50)

# 打印星号三角形
print("直角三角形：")
for i in range(1, 6):
    print("*" * i)

print("\n等腰三角形：")
for i in range(1, 6):
    spaces = " " * (5 - i)
    stars = "*" * (2 * i - 1)
    print(spaces + stars)

print("\n矩形：")
for i in range(5):
    print("* " * 8)

print()

# ==================== 9. 实战：九九乘法表 ====================
print("=" * 50)
print("9. 实战：九九乘法表（一行版）")
print("=" * 50)

for i in range(1, 10):
    for j in range(1, i + 1):
        print(f"{j}×{i}={i*j:2d}", end="  ")
    print()

print()

# ==================== 10. 实战：遍历成绩并分类 ====================
print("=" * 50)
print("10. 实战：成绩分类统计")
print("=" * 50)

scores = [95, 78, 82, 45, 90, 67, 88, 55, 92, 73]
print(f"成绩列表：{scores}")
print()

# 统计各等级人数
excellent = 0  # 优秀 >=90
good = 0       # 良好 80-89
medium = 0     # 中等 70-79
pass_count = 0 # 及格 60-69
fail = 0       # 不及格 <60

for score in scores:
    if score >= 90:
        excellent += 1
    elif score >= 80:
        good += 1
    elif score >= 70:
        medium += 1
    elif score >= 60:
        pass_count += 1
    else:
        fail += 1

print("成绩分布：")
print(f"  优秀(>=90)：{excellent}人")
print(f"  良好(80-89)：{good}人")
print(f"  中等(70-79)：{medium}人")
print(f"  及格(60-69)：{pass_count}人")
print(f"  不及格(<60)：{fail}人")

print()

# ==================== 11. 实战：购物清单 ====================
print("=" * 50)
print("11. 实战：购物清单结算")
print("=" * 50)

shopping_list = [
    {"name": "苹果", "price": 5.5, "quantity": 3},
    {"name": "香蕉", "price": 3.0, "quantity": 5},
    {"name": "橙子", "price": 4.0, "quantity": 4},
]

print("购物清单：")
print("-" * 50)
total = 0
for item in shopping_list:
    subtotal = item["price"] * item["quantity"]
    total += subtotal
    print(f"{item['name']}\t¥{item['price']} × {item['quantity']} = ¥{subtotal:.2f}")

print("-" * 50)
print(f"总计：¥{total:.2f}")

print()

# ==================== 12. 实战：字符统计 ====================
print("=" * 50)
print("12. 实战：字符串字符统计")
print("=" * 50)

text = "Hello Python Programming"
print(f"文本：{text}")
print()

# 统计各类字符数量
letters = 0
digits = 0
spaces = 0
others = 0

for char in text:
    if char.isalpha():
        letters += 1
    elif char.isdigit():
        digits += 1
    elif char.isspace():
        spaces += 1
    else:
        others += 1

print("字符统计：")
print(f"  字母：{letters}个")
print(f"  数字：{digits}个")
print(f"  空格：{spaces}个")
print(f"  其他：{others}个")
print(f"  总计：{len(text)}个")

print()

# ==================== 13. 实战：列表推导式预览 ====================
print("=" * 50)
print("13. 列表推导式（简化的for循环）")
print("=" * 50)

# 传统方式：生成1-10的平方
squares = []
for i in range(1, 11):
    squares.append(i ** 2)
print(f"传统方式：{squares}")

# 列表推导式（更简洁）
squares = [i ** 2 for i in range(1, 11)]
print(f"列表推导式：{squares}")

# 带条件的列表推导式
even_numbers = [i for i in range(1, 21) if i % 2 == 0]
print(f"\n1-20的偶数：{even_numbers}")

print()

# ==================== 14. 实战：班级成绩分析 ====================
print("=" * 50)
print("14. 实战：班级成绩全面分析")
print("=" * 50)

students = [
    {"name": "张三", "score": 85},
    {"name": "李四", "score": 92},
    {"name": "王五", "score": 78},
    {"name": "赵六", "score": 96},
    {"name": "钱七", "score": 88},
]

print("班级成绩单：")
print("-" * 50)
for i, student in enumerate(students, 1):
    print(f"{i}. {student['name']}\t{student['score']}分")

# 计算平均分
total_score = 0
for student in students:
    total_score += student["score"]
average = total_score / len(students)

print("-" * 50)
print(f"平均分：{average:.2f}分")

# 找出最高分和最低分的学生
max_student = students[0]
min_student = students[0]

for student in students:
    if student["score"] > max_student["score"]:
        max_student = student
    if student["score"] < min_student["score"]:
        min_student = student

print(f"最高分：{max_student['name']} - {max_student['score']}分")
print(f"最低分：{min_student['name']} - {min_student['score']}分")

# 统计及格人数
pass_count = 0
for student in students:
    if student["score"] >= 60:
        pass_count += 1

print(f"及格人数：{pass_count}/{len(students)}")
print(f"及格率：{pass_count/len(students)*100:.1f}%")

print()

# ==================== 15. 实战：倒计时 ====================
print("=" * 50)
print("15. 实战：倒计时")
print("=" * 50)

print("倒计时开始：")
for i in range(10, 0, -1):
    print(f"  {i}...")
print("  🎉 时间到！")

print()

# ==================== 16. 实战：斐波那契数列 ====================
print("=" * 50)
print("16. 实战：斐波那契数列")
print("=" * 50)

# 生成前10项斐波那契数列
n = 10
fib = [0, 1]
for i in range(2, n):
    next_num = fib[i-1] + fib[i-2]
    fib.append(next_num)

print(f"斐波那契数列前{n}项：")
print(fib)

print()

# ==================== 总结 ====================
print("=" * 50)
print("✨ for循环总结")
print("=" * 50)
print("""
1. 基本语法：
   for 变量 in 可迭代对象:
       循环体

2. 常见用法：
   ✅ for item in list:        遍历列表
   ✅ for char in string:      遍历字符串
   ✅ for i in range(n):       数字序列
   ✅ for key, val in dict.items():  遍历字典
   ✅ for i, item in enumerate(list):  索引和值

3. range()函数：
   - range(5)          → 0,1,2,3,4
   - range(1, 6)       → 1,2,3,4,5
   - range(0, 10, 2)   → 0,2,4,6,8
   - range(10, 0, -1)  → 10,9,8,...,1

4. 常见应用：
   - 累加求和
   - 查找最大/最小值
   - 统计分类
   - 遍历数据
   - 打印图案

5. 最佳实践：
   - 使用有意义的循环变量名
   - 避免在循环中修改被遍历的对象
   - 复杂逻辑可以提取到函数中
   - 考虑使用列表推导式简化代码
""")
print("=" * 50)

